export function loadImage(src: string | HTMLCanvasElement) {
  const img = document.createElement("img");
  return new Promise<ImageData>((resolve, reject) => {
    let canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D;
    if (typeof src === "string") {
      canvas = document.createElement("canvas");
      ctx = canvas.getContext("2d");
      img.src = src;
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        resolve(ctx.getImageData(0, 0, canvas.width, canvas.height));
      };
      img.onerror = e => reject(e);
    } else {
      canvas = src;
      ctx = src.getContext("2d");
      try {
        resolve(ctx.getImageData(0, 0, canvas.width, canvas.height));
      } catch (e) {
        reject(e);
      }
    }
  });
}

export async function getImage(
  buffers: Array<ArrayBuffer>,
  type: string = "png"
) {
  const blob = new Blob(buffers, { type: `image/${type}` });
  const url = URL.createObjectURL(blob);
  return url;
}

export async function getHead(width: number, height: number) {
  const buffer = new ArrayBuffer(13);
  const dataView = new DataView(buffer);
  dataView.setUint32(0, width);
  dataView.setUint32(4, height);
  dataView.setUint8(8, 8);
  dataView.setUint8(9, 6);
  return buffer;
}
